<?php
/**
 * Zephyr Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://code.google.com/p/zephyr-framework/wiki/License
 *
 * @category   Zephyr
 * @package    Zephyr_Validate
 * @copyright  Copyright (c) 2008 Peo Development Group (http://peo.com.pl)
 * @license    http://code.google.com/p/zephyr-framework/wiki/License     New BSD License
 * @version    $Id: SugarCrm.php 9 2008-07-23 17:33:56Z w.naruniec $
 */


/**
 * @see Zend_Loader
 */
require_once 'Zend/Loader.php';


/**
 * This class allows SugarCrm authentication credentials to be specified
 * in one place and provides a factory for returning instances of different
 * SugarCrm service classes.
 *
 * @category   Zephyr
 * @package    Zephyr_Service
 * @subpackage SugarCrm
 * @copyright  Copyright (c) 2008 Peo Development Group (http://peo.com.pl)
 * @license    http://code.google.com/p/zephyr-framework/wiki/License     New BSD License
 */
class Zephyr_Service_SugarCrm
{
    /**
     * Options to pass to Zephyr_Service_SugarCrm_Base constructor
     * @param array
     */
    protected $_options;

    /**
     * Class constructor
     *
     * @param array  $options  Options to pass to Zephyr_Service_SugarCrm_Base constructor
     */
    public function __construct($options = array())
    {
        $this->_options = $options;
    }

    /**
     * Factory method to return a preconfigured Zephyr_Service_SugarCrm_*
     * instance.
     *
     * @param  null|string  $options  Service options
     * @return object       Zephyr_Service_SugarCrm_* instance
     * @throws Zephyr_Service_SugarCrm_Exception
     */
    public function getService($options = array())
    {
        $class = isset($options['class']) ? $options['class'] : 'Base';
        unset($options['class']);

        if (strpos($class, '_') === false) {
            $class = "Zephyr_Service_SugarCrm_{$class}";
        }

        try {
            @Zend_Loader::loadClass($class);
            if (!class_exists($class, false)) {
                throw new Exception('Class file not found');
            }
        } catch (Exception $e) {
            $msg = "Service '$class' could not be loaded: " . $e->getMessage();
            /**
             * @see Zephyr_Service_SugarCrm_Exception
             */
            require_once 'Zephyr/Service/SugarCrm/Exception.php';
            throw new Zephyr_Service_SugarCrm_Exception($msg, $e->getCode());
        }

        // instantiate and return the service
        $service = new $class(array_merge($this->_options, $options));
        return $service;
    }

}
